<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="本文作者为: SylvanasSun.转载请务必将下面这段话置于文章开头处(保留超链接).本文转发自SylvanasSun Blog,原文链接: https:&#x2F;&#x2F;sylvanassun.github.io&#x2F;2017&#x2F;07&#x2F;23&#x2F;2017-07-23-Graph_DirectedGraphs&#x2F;  有向图的性质 有向图与无向图不同,它的边是单向的,每条边所连接的两个顶点都是一个有序对,它们的邻接性是">
<meta property="og:type" content="article">
<meta property="og:title" content="图的那点事儿(2)-有向图">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="本文作者为: SylvanasSun.转载请务必将下面这段话置于文章开头处(保留超链接).本文转发自SylvanasSun Blog,原文链接: https:&#x2F;&#x2F;sylvanassun.github.io&#x2F;2017&#x2F;07&#x2F;23&#x2F;2017-07-23-Graph_DirectedGraphs&#x2F;  有向图的性质 有向图与无向图不同,它的边是单向的,每条边所连接的两个顶点都是一个有序对,它们的邻接性是">
<meta property="og:locale">
<meta property="og:image" content="http://algs4.cs.princeton.edu/42digraph/images/digraph-anatomy.png">
<meta property="og:image" content="http://algs4.cs.princeton.edu/42digraph/images/digraph-api.png">
<meta property="og:image" content="http://algs4.cs.princeton.edu/42digraph/images/depth-first-orders.png">
<meta property="og:image" content="http://algs4.cs.princeton.edu/42digraph/images/topological-sort.png">
<meta property="og:image" content="http://algs4.cs.princeton.edu/42digraph/images/transitive-closure.png">
<meta property="article:published_time" content="2017-07-23T03:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="2017">
<meta property="article:tag" content="Algorithms">
<meta property="article:tag" content="Graph">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://algs4.cs.princeton.edu/42digraph/images/digraph-anatomy.png">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>图的那点事儿(2)-有向图 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%89%E5%90%91%E5%9B%BE%E7%9A%84%E6%80%A7%E8%B4%A8"><span class="nav-number">1.</span> <span class="nav-text">有向图的性质</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%89%E5%90%91%E5%9B%BE%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.</span> <span class="nav-text">有向图的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E8%BE%BE%E6%80%A7"><span class="nav-number">3.</span> <span class="nav-text">可达性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%8E%AF"><span class="nav-number">4.</span> <span class="nav-text">环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8B%93%E6%89%91%E6%8E%92%E5%BA%8F"><span class="nav-number">5.</span> <span class="nav-text">拓扑排序</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%A1%B6%E7%82%B9%E6%8E%92%E5%BA%8F"><span class="nav-number">5.1.</span> <span class="nav-text">顶点排序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%8B%93%E6%89%91%E6%8E%92%E5%BA%8F%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="nav-number">5.2.</span> <span class="nav-text">拓扑排序的实现</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%BA%E8%BF%9E%E9%80%9A%E6%80%A7"><span class="nav-number">6.</span> <span class="nav-text">强连通性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Kosaraju%E7%AE%97%E6%B3%95"><span class="nav-number">6.1.</span> <span class="nav-text">Kosaraju算法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%A0%E9%80%92%E9%97%AD%E5%8C%85"><span class="nav-number">7.</span> <span class="nav-text">传递闭包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E6%96%87%E7%8C%AE"><span class="nav-number">8.</span> <span class="nav-text">参考文献</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%BE%E7%9A%84%E9%82%A3%E7%82%B9%E4%BA%8B%E5%84%BF"><span class="nav-number">9.</span> <span class="nav-text">图的那点事儿</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          图的那点事儿(2)-有向图
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-23 11:00:00" itemprop="dateCreated datePublished" datetime="2017-07-23T11:00:00+08:00">2017-07-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Graph/" itemprop="url" rel="index"><span itemprop="name">Graph</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/</a></p>
</blockquote>
<h3 id="有向图的性质"><a href="#有向图的性质" class="headerlink" title="有向图的性质"></a>有向图的性质</h3><hr>
<p><code>有向图</code>与<code>无向图</code>不同,<strong>它的<code>边</code>是单向的,每条边所连接的两个顶点都是一个有序对,它们的邻接性是单向的.</strong></p>
<p>在<code>有向图</code>中,一条<code>有向边</code><strong>由第一个<code>顶点</code>指出并指向第二个<code>顶点</code></strong>,<strong>一个<code>顶点</code>的<code>出度</code>为由该<code>顶点</code>指出的<code>边</code>的总数;一个<code>顶点</code>的<code>入度</code>为指向该<code>顶点</code>的边的总数</strong>.</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/digraph-anatomy.png" alt="有向图的解析"></p>
<p><code>v-&gt;w</code>表示一条由<code>v</code>指向<code>w</code>的边,在一幅<code>有向图</code>中,两个<code>顶点</code>的关系可能有以下四种(特殊图除外): </p>
<ol>
<li>没有<code>边</code>相连.</li>
</ol>
<ol start="2">
<li>存在一条从<code>v</code>到<code>w</code>的<code>边</code>: <code>v-&gt;w</code>.</li>
</ol>
<ol start="3">
<li>存在一条从<code>w</code>到<code>v</code>的<code>边</code>: <code>w-&gt;v</code>.</li>
</ol>
<ol start="4">
<li>既存在<code>v-&gt;w</code>,也存在<code>w-&gt;v</code>,也就是一条<code>双向边</code>.</li>
</ol>
<p>当存在从<code>v</code>到<code>w</code>的<code>有向路径</code>时,称<code>顶点w</code>能够由<code>顶点v</code>达到.但在<code>有向图</code>中,由<code>v</code>能够到达<code>w</code>并不意味着由<code>w</code>也能到达<code>v</code>(但每个<code>顶点</code>都是能够到达它自己的).</p>
<h3 id="有向图的实现"><a href="#有向图的实现" class="headerlink" title="有向图的实现"></a>有向图的实现</h3><hr>
<p><code>有向图</code>的实现与<code>无向图</code>差不多,只不过在<code>边</code>的方向上有所不同.(本文中的所有完整代码可以在我的<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/tree/master/src/main/java/chapter4_graphs/C4_2_DirectedGraphs">GitHub</a>中查看)</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/digraph-api.png" alt="有向图的API"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Digraph</span> <span class="keyword">implements</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String NEWLINE = System.getProperty(<span class="string">&quot;line.separator&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of vertices in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> vertex;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of edges in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> edge;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// adj[v] = adjacency list for vertex v</span></span><br><span class="line">    <span class="keyword">private</span> Bag&lt;Integer&gt;[] adj;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// indegree[v] = indegree of vertex v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] indegree;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">        <span class="keyword">this</span>.edge = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.indegree = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.adj = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">            adj[i] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(Scanner scanner)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (scanner == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Scanner must be not null.&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> vertex = scanner.nextInt();</span><br><span class="line">            validateVertex(vertex);</span><br><span class="line">            <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">            <span class="keyword">this</span>.indegree = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">            <span class="keyword">this</span>.adj = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">                adj[i] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> edge = scanner.nextInt();</span><br><span class="line">            validateEdge(edge);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edge; i++) &#123;</span><br><span class="line">                <span class="keyword">int</span> v = scanner.nextInt();</span><br><span class="line">                <span class="keyword">int</span> w = scanner.nextInt();</span><br><span class="line">                addEdge(v, w);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchElementException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Invalid input format in Digraph constructor&quot;</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(digraph.vertex);</span><br><span class="line">        <span class="keyword">this</span>.edge = digraph.edge;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">this</span>.indegree[v] = digraph.indegree(v);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            Stack&lt;Integer&gt; reverse = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(v))</span><br><span class="line">                reverse.push(w);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : reverse)</span><br><span class="line">                <span class="keyword">this</span>.adj[v].add(w);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> vertex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> edge;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 注意这里与无向图不同,只在v的邻接表中添加了w</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        adj[v].add(w);</span><br><span class="line">		<span class="comment">// w的入度+ 1</span></span><br><span class="line">        indegree[w]++;</span><br><span class="line">        edge++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> indegree[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * v的出度就是它邻接表中的顶点数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">outdegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@Deprecated</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">degree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 它返回该有向图的一个副本,但所有边的方向都会被反转.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Digraph <span class="title">reverse</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Digraph reverse = <span class="keyword">new</span> Digraph(vertex);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : adj[v]) &#123;</span><br><span class="line">                reverse.addEdge(w, v);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> reverse;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        sb.append(String.format(<span class="string">&quot;Vertexes: %s, Edges: %s&quot;</span>, vertex, edge));</span><br><span class="line">        sb.append(NEWLINE);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            sb.append(String.format(<span class="string">&quot;vertex %d, &quot;</span>, v));</span><br><span class="line">            sb.append(String.format(<span class="string">&quot;indegree: %d, outdegree: %d&quot;</span>, indegree(v), outdegree(v)));</span><br><span class="line">            sb.append(NEWLINE);</span><br><span class="line">            sb.append(<span class="string">&quot;adjacent point: &quot;</span>);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : adj[v])</span><br><span class="line">                sb.append(w).append(<span class="string">&quot; &quot;</span>);</span><br><span class="line"></span><br><span class="line">            sb.append(NEWLINE);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateEdge</span><span class="params">(<span class="keyword">int</span> edge)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (edge &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of edges in a Digraph must be nonnegative.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of vertex in a Digraph must be nonnegative.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="可达性"><a href="#可达性" class="headerlink" title="可达性"></a>可达性</h3><hr>
<p>对于”是否存在一条从集合中的任意<code>顶点</code>到达给定<code>顶点v</code>的有向路径?”等类似问题,可以使用<code>深度优先搜索</code>或<code>广度优先搜索</code>(与<code>无向图</code>的实现一致,只不过传入的<code>图</code>的类型不同),<code>有向图</code>生成的搜索轨迹甚至要比<code>无向图</code>还要简单.</p>
<p>对于<code>可达性分析</code>的一个典型应用就是内存管理系统.例如,<code>JVM</code>使用<code>多点可达性分析</code>的方法来判断一个<code>对象</code>是否可以进行回收: 所有<code>对象</code>组成一幅<code>有向图</code>,其中有多个<code>Root顶点</code>(它是由<code>JVM</code>自己决定的)作为<code>起点</code>,如果一个<code>对象</code>从<code>Root顶点</code>不可达,那么这个<code>对象</code>就可以进行回收了.</p>
<h3 id="环"><a href="#环" class="headerlink" title="环"></a>环</h3><hr>
<p>在与<code>有向图</code>相关的实际应用中,<code>有向环</code>特别的重要.我们需要知道一幅<code>有向图</code>中是否包含<code>有向环</code>.在任务调度问题或其他许多问题中会不允许存在<code>有向环</code>,所以对于<code>环</code>的检测是很重要的.</p>
<p>使用<code>深度优先搜索</code>解决这个问题并不困难,递归调用隐式使用的栈表示的正是”当前”正在遍历的<code>有向路径</code>,一旦找到了一条<code>边v-&gt;w</code>且<code>w</code>已经存在于栈中,就等于找到了一个<code>环</code>(栈表示的是一条由<code>w</code>到<code>v</code>的<code>有向路径</code>,而<code>v-&gt;w</code>正好补全了这个<code>环</code>).</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DirectedCycle</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Digraph digraph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has vertex v been marked?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// edgeTo[v] = previous vertex on path to v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// onStack[v] = is vertex on the stack?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] onStack;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// directed cycle (or null if no such cycle)</span></span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; cycle;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DirectedCycle</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.digraph = digraph;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.onStack = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">			<span class="comment">// 已经找到环时就不再需要继续搜索了</span></span><br><span class="line">            <span class="keyword">if</span> (!marked[v] &amp;&amp; cycle == <span class="keyword">null</span>)</span><br><span class="line">                dfs(v);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasCycle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cycle != <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">cycle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cycle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">        onStack[vertex] = <span class="keyword">true</span>; <span class="comment">// 用于模拟递归调用栈</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (cycle != <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (!marked[w]) &#123;</span><br><span class="line">                edgeTo[w] = vertex;</span><br><span class="line">                dfs(w);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (onStack[w]) &#123;</span><br><span class="line">				<span class="comment">// 当w已被标记且在栈中时: 找到环</span></span><br><span class="line">                cycle = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> x = vertex; x != w; x = edgeTo[x])</span><br><span class="line">                    cycle.push(x);</span><br><span class="line">                cycle.push(w);</span><br><span class="line">                cycle.push(vertex);</span><br><span class="line">                <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">()</span></span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">// 这条路径已经到头,从栈中弹出</span></span><br><span class="line">        onStack[vertex] = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// certify that digraph has a directed cycle if it reports one</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (hasCycle()) &#123;</span><br><span class="line">            <span class="comment">// verify cycle</span></span><br><span class="line">            <span class="keyword">int</span> first = -<span class="number">1</span>, last = -<span class="number">1</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> v : cycle()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (first == -<span class="number">1</span>) first = v;</span><br><span class="line">                last = v;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (first != last) &#123;</span><br><span class="line">                System.err.printf(<span class="string">&quot;cycle begins with %d and ends with %d\n&quot;</span>, first, last);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="拓扑排序"><a href="#拓扑排序" class="headerlink" title="拓扑排序"></a>拓扑排序</h3><hr>
<p><code>拓扑排序</code>等价于计算优先级限制下的调度问题的,所谓优先级限制的调度问题即是在给定一组需要完成的任务与关于任务完成的先后次序的优先级限制,需要在满足限制条件的前提下来安排任务.</p>
<p><code>拓扑排序</code>需要的是一幅<code>有向无环图</code>,如果这幅<code>图</code>中含有<code>环</code>,那么它肯定不是<code>拓扑有序</code>的(一个带有环的调度问题是无解的).</p>
<p>在学习<code>拓扑排序</code>之前,需要先知道<code>顶点</code>的排序.</p>
<h4 id="顶点排序"><a href="#顶点排序" class="headerlink" title="顶点排序"></a>顶点排序</h4><hr>
<p>使用<code>深度优先搜索</code>来记录<code>顶点排序</code>是一个很好的选择(正好只会访问每个<code>顶点</code>一次),我们借助一些<code>数据结构</code>来保存<code>顶点排序</code>的顺序: </p>
<ul>
<li>前序: 在递归调用之前将<code>顶点</code>加入队列.</li>
</ul>
<ul>
<li>后序: 在递归调用之后将<code>顶点</code>加入队列.</li>
</ul>
<ul>
<li>逆后序: 在递归调用之后将<code>顶点</code>压入栈.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/depth-first-orders.png" alt="顶点排序的轨迹"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DepthFirstOrder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has v been marked in dfs?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// pre[v]    = preorder  number of v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] pre;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// post[v]   = postorder number of v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] post;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// vertices in preorder</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Integer&gt; preorder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// vertices in postorder</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Integer&gt; postorder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// counter or preorder numbering</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> preCounter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// counter for postorder numbering</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> postCounter;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DepthFirstOrder</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.pre = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.post = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.preorder = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.postorder = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) dfs(v);</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">()</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">pre</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> pre[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">post</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> post[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">post</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> postorder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">pre</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> preorder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 逆后序,遍历后序队列并压入栈中</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">reversePost</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Stack&lt;Integer&gt; reverse = <span class="keyword">new</span> Stack&lt;Integer&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : postorder)</span><br><span class="line">            reverse.push(v);</span><br><span class="line">        <span class="keyword">return</span> reverse;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">		<span class="comment">// 前序</span></span><br><span class="line">        pre[vertex] = preCounter++;</span><br><span class="line">        preorder.add(vertex);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w])</span><br><span class="line">                dfs(w);</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">// 后序</span></span><br><span class="line">        post[vertex] = postCounter++;</span><br><span class="line">        postorder.add(vertex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// check that pre() and post() are consistent with pre(v) and post(v)</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that post(v) is consistent with post()</span></span><br><span class="line">        <span class="keyword">int</span> r = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : post()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (post(v) != r) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;post(v) and post() inconsistent&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            r++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that pre(v) is consistent with pre()</span></span><br><span class="line">        r = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : pre()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (pre(v) != r) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;pre(v) and pre() inconsistent&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            r++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="拓扑排序的实现"><a href="#拓扑排序的实现" class="headerlink" title="拓扑排序的实现"></a>拓扑排序的实现</h4><hr>
<p>所谓<code>拓扑排序</code>就是<code>无环有向图</code>的<code>逆后序</code>,现在已经知道了如何检测<code>环</code>与<code>顶点排序</code>,那么实现<code>拓扑排序</code>就很简单了.</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/topological-sort.png"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Topological</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// topological order</span></span><br><span class="line">    <span class="keyword">private</span> Iterable&lt;Integer&gt; order;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// rank[v] = position of vertex v in topological order</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] rank;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Topological</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        DirectedCycle directedCycle = <span class="keyword">new</span> DirectedCycle(digraph);</span><br><span class="line">		<span class="comment">// 只有这幅图没有环时,才进行计算拓扑排序</span></span><br><span class="line">        <span class="keyword">if</span> (!directedCycle.hasCycle()) &#123;</span><br><span class="line">            DepthFirstOrder depthFirstOrder = <span class="keyword">new</span> DepthFirstOrder(digraph);</span><br><span class="line">			<span class="comment">// 拓扑排序即是逆后序</span></span><br><span class="line">            order = depthFirstOrder.reversePost();</span><br><span class="line">            rank = <span class="keyword">new</span> <span class="keyword">int</span>[digraph.vertex()];</span><br><span class="line">            <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> v : order)</span><br><span class="line">                rank[v] = i++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">order</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> order;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> order != <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">rank</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">if</span> (hasOrder()) <span class="keyword">return</span> rank[v];</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = rank.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="强连通性"><a href="#强连通性" class="headerlink" title="强连通性"></a>强连通性</h3><hr>
<p>在一幅<code>无向图</code>中,如果有一条路径连接顶点<code>v</code>和<code>w</code>,则它们就是<code>连通</code>的(既可以从<code>w</code>到达<code>v</code>,也可以从<code>v</code>到达<code>w</code>).但在<code>有向图</code>中,如果从顶点<code>v</code>有一条有向路径到达<code>w</code>,则<code>w</code>是从<code>v</code>可达的,但从<code>w</code>到达<code>v</code>的路径可能存在也可能不存在.</p>
<p><strong><code>强连通性</code>就是两个顶点<code>v</code>和<code>w</code>是互相可达的.</strong><code>有向图</code>中的<code>强连通性</code>具有以下性质: </p>
<ul>
<li>自反性: 任意<code>顶点v</code>和自己都是<code>强连通性</code>的(<code>有向图</code>中顶点都是自己可达的).</li>
</ul>
<ul>
<li>对称性: 如果<code>v</code>和<code>w</code>是强连通的,那么<code>w</code>和<code>v</code>也是强连通的.</li>
</ul>
<ul>
<li>传递性: 如果<code>v</code>和<code>w</code>是强连通的且<code>w</code>和<code>x</code>也是强连通的,那么<code>v</code>和<code>x</code>也是强连通的.</li>
</ul>
<p><code>强连通性</code>将所有<code>顶点</code>分为了一些等价类,每个等价类都是由相互为强连通的<code>顶点</code>的最大子集组成的.这些子集称为<code>强连通分量</code>,它的定义是基于顶点的,而非边.</p>
<p>一个含有<code>V</code>个顶点的<code>有向图</code>含有<code>1 ~ V</code>个<code>强连通分量</code>.一个<code>强连通图</code>只含有一个<code>强连通分量</code>,而一个<code>有向无环图</code>中则含有<code>V</code>个<code>强连通分量</code>.</p>
<h4 id="Kosaraju算法"><a href="#Kosaraju算法" class="headerlink" title="Kosaraju算法"></a>Kosaraju算法</h4><hr>
<p><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm">Kosaraju</a>算法是用于枚举图中每个<code>强连通分量</code>内的所有顶点,它主要有以下步骤: </p>
<ul>
<li>在给定一幅<code>有向图</code>$G$中,取得它的反向图$G^R$.</li>
</ul>
<ul>
<li>利用<code>深度优先搜索</code>得到$G^R$的逆后序排列.</li>
</ul>
<ul>
<li>按照上述逆后序的序列进行<code>深度优先搜索</code></li>
</ul>
<ul>
<li>同一个<code>深度优先搜索</code>递归子程序中访问的所有<code>顶点</code>都在同一个<code>强连通分量</code>内.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">KosarajuSharirSCC</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Digraph digraph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has vertex v been visited?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// id[v] = id of strong component containing v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] id;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of strongly-connected components</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> count;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">KosarajuSharirSCC</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.digraph = digraph;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// compute reverse postorder of reverse graph</span></span><br><span class="line">        DepthFirstOrder depthFirstOrder = <span class="keyword">new</span> DepthFirstOrder(digraph.reverse());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// run DFS on G, using reverse postorder to guide calculation</span></span><br><span class="line">        marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        id = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : depthFirstOrder.reversePost()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) &#123;</span><br><span class="line">                dfs(v);</span><br><span class="line">                count++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that id[] gives strong components</span></span><br><span class="line">        <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">(digraph)</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line">        id[v] = count;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w])</span><br><span class="line">                dfs(w);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">count</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">stronglyConnected</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        <span class="keyword">return</span> id[v] == id[w];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">id</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> id[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// does the id[] array contain the strongly connected components?</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">(Digraph G)</span> </span>&#123;</span><br><span class="line">        TransitiveClosure tc = <span class="keyword">new</span> TransitiveClosure(G);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; G.vertex(); v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w = <span class="number">0</span>; w &lt; G.vertex(); w++) &#123;</span><br><span class="line">                <span class="keyword">if</span> (stronglyConnected(v, w) != (tc.reachable(v, w) &amp;&amp; tc.reachable(w, v)))</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="传递闭包"><a href="#传递闭包" class="headerlink" title="传递闭包"></a>传递闭包</h3><hr>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/transitive-closure.png"></p>
<p>在一幅有向图<code>G</code>中,<code>传递闭包</code>是由相同的一组<code>顶点</code>组成的另一幅<code>有向图</code>,在<code>传递闭包</code>中存在一条从<code>v</code>指向<code>w</code>的边且仅当在<code>G</code>中<code>w</code>是从<code>v</code>可达的.</p>
<p>由于<code>有向图</code>的性质,每个<code>顶点</code>对于自己都是可达的,所以<code>传递闭包</code>会含有<code>V</code>个自环.</p>
<p>通常将<code>传递闭包</code>表示为一个布尔值矩阵,其中<code>v</code>行<code>w</code>列的值为<code>true</code>代表当且仅当<code>w</code>是从<code>v</code>可达的.</p>
<p><code>传递闭包</code>不适合于处理<code>大型有向图</code>,因为构造函数所需的空间与$V^2$成正比,所需的时间和$V(V+E)$成正比.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TransitiveClosure</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> DirectedDFS[] tc;  <span class="comment">// tc[v] = reachable from v</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">TransitiveClosure</span><span class="params">(Digraph G)</span> </span>&#123;</span><br><span class="line">        tc = <span class="keyword">new</span> DirectedDFS[G.vertex()];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; G.vertex(); v++)</span><br><span class="line">            tc[v] = <span class="keyword">new</span> DirectedDFS(G, v);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">reachable</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        <span class="keyword">return</span> tc[v].marked(w);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = tc.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/42digraph/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm">Kosaraju’s algorithm - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Transitive_closure">Transitive closure - Wikipedia</a></li>
</ul>
<h3 id="图的那点事儿"><a href="#图的那点事儿" class="headerlink" title="图的那点事儿"></a>图的那点事儿</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">图的那点事儿(1)-无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">图的那点事儿(2)-有向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">图的那点事儿(3)-加权无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">图的那点事儿(4)-加权有向图</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/2017/" rel="tag"># 2017</a>
              <a href="/yuwanzi.io/tags/Algorithms/" rel="tag"># Algorithms</a>
              <a href="/yuwanzi.io/tags/Graph/" rel="tag"># Graph</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/07/19/2017-07-19-FaceMash/" rel="prev" title="电影<<社交网络>>中的"FaceMash"算法">
                  <i class="fa fa-chevron-left"></i> 电影<<社交网络>>中的"FaceMash"算法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/" rel="next" title="图的那点事儿(3)-加权无向图">
                  图的那点事儿(3)-加权无向图 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
